const _getSo = Symbol("_getSo"),
    _getHttp = Symbol('_getHttp'),
    _logOut = Symbol('_logOut'),
    _loginSuccess = Symbol('_loginSuccess'),
    _login = Symbol('_login'),
    _setTime = Symbol('_setTime');
export default class Login {
    socket = {}
    so = null
    constructor(socket) {
        this.socket = socket;
        this.so = null
    }
    sendMessage() {
        return { code: 200, data: '成功' }
    }
    /*收到服务器回执信息的处理*/
    receiptMsg(data) {
        let res = data.body;
        let { member_id } = res.data.userData;
        this.socket.heart.init(this.socket.so);                                            // 心跳初始化
        this.socket.heart.start(member_id);                                                // 心跳开始
        this[_loginSuccess](res);
        return res;
    }
    /*接受服务器消息的处理*/
    getMsg(msg) {
        this[_logOut]();
        return { code: 301, data: '收到服务器消息，被踢下线！' }
    }
    /*登录成功后执行*/
    [_loginSuccess](res) {
        let member_id = res.data.userData.member_id,
            loginData = sessionStorage.getItem("loginData"),
            port = this.socket.api.loginData.port,
            config = this.socket.api.config;
        loginData = JSON.parse(loginData);
        let { token, key } = loginData;
        //自动重连属性
        this.socket.api.userLoginStatus.isOnLine = true;                                              // 改变登录状态
        this.socket.api.userLoginStatus.userSelect = 0;                                               // 初始化用户选择
        this.socket.api.userLoginStatus.leaveType = 0;
        //用户基本属性  
        this.socket.api.loginData.userData.token = token;
        this.socket.api.loginData.userData.key = key;
        this.socket.api.loginData.userData.member_id = member_id;
        this.socket.storage.setStorageProperty('config',config)
        this.socket.storage.saveBySessionStorage('config',config)
        this.socket.storage.setStorageProperty('property',res.data.userData)
        this.socket.storage.init(this.socket)
        this.socket.storage.setStorageProperty('loginData', {key, token, member_id, port})
        this.socket.storage.setProperty(this.socket)
        this[_setTime]();                                                                   // 检测断线
        res.data.msgList.forEach(item => { this.socket.receiverController.receiverMsg(item) });    // 执行离线消息执行一遍
        this.socket.api.loginData.onLoginSuccess && this.socket.api.loginData.onLoginSuccess({                  // 登录成功，用户的回调函数          
            userData: res.data.userData,
            token,
        })
    }
    /*强制登出*/
    [_logOut]() {
        var that = this;
        that.socket.api.userLoginStatus.isOnLine = false;
        that.socket.api.userLoginStatus.userSelect = 0;
        that.socket.api.userLoginStatus.leaveType = 1;
        that.so = null;
        //3.获取用户的选择，根据用户的选择进行操作
        const res = that.socket.api.loginData.onCloseCallback();
        if (res) {
            //4.当用户同意连接时，改变userLoginStatus断线状态、断线原因。
            that.socket.api.userLoginStatus.userSelect = 1
        } else {
            //5.当用户拒绝连接时，清空userLoginStatus定时器(循环检测用户状态的函数)、本地会话存储。不再连接。 
            that.socket.api.userLoginStatus.userSelect = 2;
            sessionStorage.clear();
            clearInterval(that.socket.api.userLoginStatus.timeOff);
            that.socket.api.userLoginStatus.timeOff = '';
        }
    }
    /*定时检测so是否断开连接*/
    [_setTime]() {
        const controller = this.socket.api.userLoginStatus;
        if (controller.timeOff) { return }                                                                   //防止重复开启定时器
        controller.timeOff = setInterval(() => {
            if (controller.isOnLine) { return }                                                               //在线不操作或者初始化                       
            if (controller.leaveType == 1) {                                                                 //被踢下线
                if (controller.userSelect == 1) {
                    this.so = null;
                    this[_login]('', '', this.socket.api.loginData.userData.key, this.socket.api.loginData.userData.token);
                }
                else if (controller.userSelect == 2) { clearInterval(controller.timeOff); sessionStorage.clear(); }
                return { code: 301, data: '断线提示：强制登出!' }
            }
            if (controller.leaveType === 0) { return }
            clearInterval(controller.timeOff);
            controller.timeOff = '';
            const res = confirm("你已经断开连接，你需要重新连接吗？");
            if (res) {
                this[_login]('', '', this.socket.api.loginData.userData.key, this.socket.api.loginData.userData.token)
                this[_setTime]();
            } else {
                sessionStorage.clear();
            }
        }, 5000);
    }
    /*登录*/
    [_login](username, password, key, token) {
        let member_id = this.socket.api.loginData.userData.member_id,
            port = this.socket.api.loginData.port,
            config = this.config
        // so 已经连接
        let initConfig = sessionStorage.getItem('config');
            if(initConfig){
                config = JSON.parse(initConfig)
            }
        if (this.so && this.so.readyState == 1) {
            return { code: 301, data: "不要重复登录！" }
        }
        var that = this;
        that[_getHttp](
            config['h_url'] + "/getLoginKey",
            { token, port: config.port },
            function (data) {
                if (data.code == 200) {
                    var loginKey = data.data.loginKey;
                    var isForceLogin = data.data.isNeedForceLogin;
                    let url = "ws://" + config['e_url'] + ":" + 2345/* that.socket.port */;                   //url='ws://e.com:2345';
                    that.socket.storage.saveBySessionStorage('loginData', {key,token,member_id,port})
                    that[_getSo](url, key, loginKey, token, isForceLogin, that.socket.api.loginData.sertype);
                }
            }
        );
    }
    /*socket连接 ，so监听事件*/
    [_getSo](url, key, loginKey, token, isForceLogin, sertype, callback, failCallback) {
        for (let i in arguments) {
            if (arguments[i] == undefined || arguments[i] == '') {
                console.log("getSo,第" + i + "个参数不能为空！");
            }
        }
        const that = this;
        if (this.so == null) {
            this.so = new WebSocket(url);
            this.so.onerror = () => { return {code :200 ,data:'so连接失败'} };
            that.so.onopen = function () {
                if (that.so && that.so.readyState == 1) {
                    that.socket.receiverController.so = that.socket.receiverController.so = that.so;
                    const msg = that.socket.sendController.sendServerMsg("login", { key, loginKey, token, sertype, isForceLogin }, that.socket.api.loginData.userData.member_id, (data) => {
                        if (data.body.code == 200) { callback && callback(data.body) } else { failCallback && failCallback(data.body); }
                    });
                    if (msg.code != 200) {
                        alert("消息创建失败！");
                        return { code: 301, data: '消息创建失败！' }
                    }
                    that.socket.sendController._sendMessage(msg.data.data.head.clientMsgId);
                }
            };
            this.so.onmessage = function (msg) {
                var data = JSON.parse(msg.data);
                if (data.head.ms == 1) {                            //服务端发送的数据
                    that.socket.receiverController.receiverMsg(data);
                } else {
                    that.socket.sendController._getServerReceiptMsg(data);   //回执消息的处理  
                }
            };
            this.so.onclose = function () {
                if (that.socket.api.userLoginStatus.leaveType != 1) { that.socket.api.userLoginStatus.leaveType = 2; that.so = null; }
                that.socket.api.userLoginStatus.isOnLine = false;
                that.socket.api.loginData.onConnectClose ? that.socket.api.loginData.onConnectClose() : '';               //socket断开回调 
                that.socket.heart.stop();                                                                    //停止心跳检测
                that.socket.friendObject.clear();
                that.socket.talkObject.clear();
            };
            this.socket.so = this.so
        }
    }
    /*请求*/
    [_getHttp](url, params, callback) {
        for (let i in arguments) {
            if (arguments[i] == undefined || arguments[i] == '') {
                alert("getHttp参数，第 " + i + "个参数不能为空！");
                return
            }
        }
        var xmlpost = new XMLHttpRequest();
        xmlpost.open("post", url, true);
        var postData = [];
        if (params) {
            for (let i in params) {
                postData.push(i + "=" + params[i]);
            }
            postData = postData.join("&");
        }
        xmlpost.send(postData);
        xmlpost.onreadystatechange = function () {
            if (xmlpost.readyState == 4) {
                if (xmlpost.status == 200) {
                    var data = JSON.parse(xmlpost.responseText);
                    callback(data);
                    if (data.code != 200) {
                        console.log("请求出错", data.data);
                    }
                }
            }
        };
    }
}